//
//  PaymentViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/18.
//

import UIKit

typealias BlockPushFirstData = (_ urlStr: String)->Void

class PaymentViewController: BaseViewController {
    var pushFirstDataBlock: BlockPushFirstData!
    var bgView: UIView!
    var titleLab: UILabel!
    var priceLab: UILabel!
    var tableView: BaseTableView!
    var dataArr: [String] = [MMLocalizedString("confirm_first_pay", comment: "FirstData支付")]
    var orderContentModel = OrderContentListModel()
    var paymentTransactionSn: String = "" //支付返回的编号，查询订单用
    var getOrderPayStatusCount: NSInteger = 0
    var paymentBtn: LoaddingButton!
    var pageType: NSInteger = 0 //0：商品直接支付进来(没有取price)  1：订单列表进来(取depositAmount)
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.barBackgroundColor = .clear
        self.view.backgroundColor = .clear
        self.initUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.startAnimation()
    }
    
    func initUI(){
        let contor = UIControl(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
        contor.backgroundColor = .black
        contor.alpha = 0.7
        self.view.addSubview(contor)
        
        self.bgView = UIView(frame: CGRect(x: 0, y: kScreenHeight - 266, width: kScreenWidth, height: 266))
        self.bgView.backgroundColor = .white
        self.bgView.layer.cornerRadius = 10
        self.bgView.layer.masksToBounds = true
        self.view.addSubview(self.bgView)
        
        titleLab = UILabel(frame: CGRect(x: 0, y: 20, width: kScreenWidth, height: 20))
        titleLab.textColor = .black
        titleLab.font = UIFont(name: Theme.PingFangSCMedium, size: 16)
        titleLab.textAlignment = .center
        titleLab.text = MMLocalizedString("pay_order", comment: "支付订单")
        bgView.addSubview(titleLab)
        
        priceLab = UILabel(frame: CGRect(x: 14, y: titleLab.frame.maxY + 40, width: kScreenWidth - 28, height: 33))
        priceLab.textColor = Theme.mainColor
        priceLab.font = UIFont(name: Theme.PingFangSCMedium, size: 24)
        priceLab.textAlignment = .center
        
        var price = ""
        if self.pageType == 0 {
            price = XTManageCenter.showPriceInComma(source: (self.orderContentModel.price ?? 0).cleanZero)
        }else{
            price = XTManageCenter.showPriceInComma(source: (self.orderContentModel.depositAmount ?? 0).cleanZero)
        }
        priceLab.text = XTManageCenter.currentSign() + price
        bgView.addSubview(priceLab)

        
        self.tableView = BaseTableView.init(frame: CGRect.init(x: 0, y: priceLab.frame.maxY + 10, width: kScreenWidth, height: 60), style: .grouped)
        self.tableView.register(PayTypeCell.self, forCellReuseIdentifier: "PayTypeCell")
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.backgroundColor = UIColor.white
        self.tableView.separatorStyle = .none
        self.tableView.isScrollEnabled = false
        self.bgView.addSubview(self.tableView)
        
        self.paymentBtn = LoaddingButton(frame: CGRect(x: 14, y: self.bgView.frame.size.height - 86, width: self.bgView.frame.size.width - 28 , height: 46))
        self.paymentBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        self.paymentBtn.setTitleColor(Theme.whiteColor, for: .normal)
        self.paymentBtn.layer.cornerRadius = 8
        self.paymentBtn.layer.masksToBounds = true
        self.paymentBtn.titleLabel?.lineBreakMode = .byWordWrapping
        self.paymentBtn.titleLabel?.numberOfLines = 0
        self.paymentBtn.addTarget(self, action: #selector(paymentBtnAntion), for: .touchUpInside)
        self.paymentBtn.setTitle(MMLocalizedString("pay_now", comment: "立即支付"), for: .normal)
        self.paymentBtn.backgroundColor = Theme.mainColor
        self.bgView.addSubview(self.paymentBtn)
    
        
        let hideBtn = UIButton(frame: CGRect(x: kScreenWidth - 40, y: 10, width: 30, height: 30))
        hideBtn.setImage(UIImage(named: "icon_close"), for: .normal)
        hideBtn.addTarget(self, action: #selector(handleClose), for: .touchUpInside)
        self.bgView.addSubview(hideBtn)
    }
    
    private func startAnimation(){
        self.bgView.frame.origin.y = kScreenHeight
        UIView.animate(withDuration: 0.24) {
            self.bgView.frame.origin.y = kScreenHeight - self.bgView.frame.size.height
        }
    }
    
    ///创建订单
        func createOrder(){
            self.paymentBtn.showLoading()
            //self.view.showLoadingHUDText(nil)
            let param: [String: String] = ["paymentPluginId":"firstDataPaymentPlugin",
                                           "isPay":"1",
                                           "paymentItemList[0].type":"ORDER_PAYMENT",
                                           "paymentItemList[0].amount":"\(self.orderContentModel.price ?? 0)",
                                           "paymentItemList[0].sn":"\(self.orderContentModel.orderNo ?? "")",
                                           "rePayUrl":"/"]
            XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.createOrder(param: param), objectType: PaymentResModel.self) { data in
                //self.view.handleLoading()
                self.paymentBtn.handleLoadding()
                let resultObj = data as! PaymentResModel
                let payUrl = resultObj.extData?.pay?.paymentURL ?? ""
                if resultObj.code == "1" && payUrl != "" {
                    self.paymentTransactionSn = resultObj.extData?.pay?.paymentTransactionSn ?? ""
                    UIView.animate(withDuration: 0.24) {
                        self.bgView.frame.origin.y = kScreenHeight
                    } completion: { flag in
                        self.dismiss(animated: false) {
                            self.pushFirstDataBlock?(payUrl)
                        }
                    }
                }else{
                    self.view.makeToastBottom(message: resultObj.msg ?? "")
                }
            } error: { err in
                self.paymentBtn.handleLoadding()
                //self.view.handleLoading()
                self.view.makeToastBottom(message: err?.domain ?? "")
            }
        }
        
        ///查询支付结果
        func fetchGetOrderStatus() {
            self.view.showLoadingHUDText(nil)
            XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.paymentDetail(param: [
                "paymentTransactionSn": self.paymentTransactionSn
            ]), objectType: PaymentResModel.self) { data in
                let resultObj = data as! PaymentResModel
                self.view.handleLoading()
                if resultObj.code == "1" && (resultObj.data?.isSuccess ?? false){
                    self.jumpToPayResultAction(status: true)
                }else{
                    if self.getOrderPayStatusCount == 0 {
                        XTAlertView.showHKPayDetailAlertView(title: "",
                                                             message: MMLocalizedString("pay_failed", comment: "支付失败"),
                                                             cancelButtonTitle: MMLocalizedString("i_paid", comment: "我已支付"),
                                                             otherButtonTitles: MMLocalizedString("closed", comment: "关闭")) { (alert, tag) in
                            if tag == 1 {
                                //关闭
                            }else{
                                //我已支付 再查询一次
                                self.getOrderPayStatusCount = 1
                                self.fetchGetOrderStatus()
                            }
                        }
                    }else{
                        self.jumpToPayResultAction(status: false)
                    }
                }
            } error: { err in
                self.view.handleLoading()
                self.view.makeToastBottom(message: err?.domain ?? "")
            }
        }
    
    
    ///支付结果
    func jumpToPayResultAction(status: Bool) {
        self.paymentTransactionSn = ""
        let vc = PayResultViewController()
        vc.payStatus = status
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //MARK: - Antion
    @objc func handleClose(){
        XTAlertView.showAlertView(title: MMLocalizedString("hint", comment: "提示"),
                                  message: MMLocalizedString("sure_cancel_payment", comment: "确定取消支付吗？"),
                                  cancelButtonTitle: MMLocalizedString("cancel", comment: "取消"),
                                  otherButtonTitlesArr: [MMLocalizedString("confirm", comment: "确定")]) { alert, tag in
            if tag == 1 {
                self.closeAnimatonAction()
            }
        }
    }
    
    ///关闭动画
    private func closeAnimatonAction(){
        UIView.animate(withDuration: 0.24) {
            self.bgView.frame.origin.y = kScreenHeight
        } completion: { flag in
            self.dismiss(animated: false)
        }
    }
    
    @objc func paymentBtnAntion(){
        self.createOrder()
    }

}

extension PaymentViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 52
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenHeight, height: 0.1))
        return header
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenHeight, height: 0.1))
        return footer
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PayTypeCell", for: indexPath) as! PayTypeCell
        if self.dataArr.count > indexPath.row {
            cell.titleLab.text = self.dataArr[indexPath.row]
        }
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //
    }
}

